package com.huluobo.a2307douyindemo.demo.lifeCycle

import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import com.huluobo.a2307douyindemo.MainActivity
import com.huluobo.a2307douyindemo.databinding.ActivityLifeCycleBinding
import com.huluobo.a2307douyindemo.demo.viewbinding.BaseActivity2

class LifeCycleActivity : BaseActivity2<ActivityLifeCycleBinding>() {
    //声明ViewModel
    private lateinit var adViewModel: ADViewModel
    override fun initData() {
        //通过反射的机制拿到对应的ViewModel
        adViewModel = ViewModelProvider(this)[ADViewModel::class.java]

        val adManager = AdManager(adViewModel)//相当于在sp中的取值
        lifecycle.addObserver(adManager)

        //观察ViewModel中LiveData的数据变化
        adViewModel.timingResult.observe(this) {
            binding.time.text = "广告剩余时间:${(it / 1000).toInt()}秒"
            if (it < 999L) {
                val intent = Intent(this@LifeCycleActivity, MainActivity::class.java)
                this@LifeCycleActivity.startActivity(intent)
                this@LifeCycleActivity.finish()
            }
        }

//        //实现接口
//        adManager.setAdManagerListener(object : AdManager.AdManagerListener {
//            override fun timing(second: Int) {
//                //当计时时
//                binding.time.text = "广告剩余时间:$second 秒"
//                adViewModel.timing = second.toLong() * 1000
//            }
//
//            override fun finish() {
//                //当结束时
//                Log.e("TagA", "结束跳转")
//                val intent = Intent(this@LifeCycleActivity, MainActivity::class.java)
//                this@LifeCycleActivity.startActivity(intent)
//                this@LifeCycleActivity.finish()
//            }
//        })
    }

    override fun initView() {
    }

    override fun getViewBinding(): ActivityLifeCycleBinding {
        return ActivityLifeCycleBinding.inflate(layoutInflater)
    }
}